#include "XVideoThread.h"
#include "XDecode.h"
#include <QDebug>
bool XVideoThread::RepaintPts(AVPacket * pkt, long long seekpts)
{
	videomux.lock();
	bool re = decode->Send(pkt);
	if (!re) {
		videomux.unlock();
		return true;//表示结束解码
	}
	AVFrame *frame = decode->Recv();
	if (!frame) {
		videomux.unlock();
		return false;
	}
	//到达位置显示
	if (decode->pts >= seekpts) {
		if (call) {
			call->Repaint(frame);
		}
		videomux.unlock();
		return true;
	}
	XFreeFrame(&frame);
	videomux.unlock();
	return false;
}
bool XVideoThread::Open(AVCodecParameters * para, IVideoCall * call, int width, int height)
{
	if (!para) {
		qDebug() << "XaudioThread::Open para is NULL";
		return false;
	}
	Clear();
	
	videomux.lock();
	synpts = 0;
	//初始化显示窗口
	this->call = call;
	if (call) {
		call->Init(width, height);
	}
	videomux.unlock();
	//打开解码器
	
	int re = true;
	if (!(decode->Open(para))) {
		qDebug() << "audio XDecode open failed";
		re = false;
	}
	qDebug() << "XAudioThred::Open value = " << re;
	return re;
}

void XVideoThread::run()
{

	while (!isExit) {
		if (this->Pause) {
			msleep(5);
			continue;
		}
		videomux.lock();
		//音视频同步，视频解码比外部传进的时间快，就等待
		if (synpts < decode->pts) {
			//qDebug() << "video decode pts" << decode->pts;
			videomux.unlock();
			msleep(10);
			continue;
		}

		AVPacket *pkt = Pop();

		bool re = decode->Send(pkt);

		if (!re) {
			//qDebug() << "failed to Send";
			videomux.unlock();
			msleep(1);
			continue;
		}
		//一次send多次 recv
		while (!isExit) {
			AVFrame *frame = decode->Recv();
			if (!frame) {
				//qDebug() << "faile to Recv";
				break;
			}
			if (call) {
				call->Repaint(frame);
			}
			//call->Repaint(frame);
			
		}
		videomux.unlock();
	}
}

XVideoThread::XVideoThread()
{
}

XVideoThread::~XVideoThread()
{

}

void XVideoThread::SetPause(bool isPause)
{
	videomux.lock();
	this->Pause = isPause;
	videomux.unlock();
}
